package com.wdc.deliveryrobot.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sirui.selfstudysdk.mode.MapData;
import com.wdc.deliveryrobot.Sp.SPManager;
import com.wdc.deliveryrobot.model.PointOne;

import java.util.ArrayList;
import java.util.List;

public class MapEditView extends View {

    private JSONObject jsonObjectScan;

    private MapData mapData;

    private SPManager spManager;
    private double[] distances;

    private float scaleFactor = 1.0f; // 当前缩放比例
    private float focusX; // 缩放中心 X 坐标
    private float focusY; // 缩放中心 Y 坐标

    private float offsetX = 0; // X 轴偏移
    private float offsetY = 0; // Y 轴偏移
    private float lastTouchX; // 上一个触摸点 X
    private float lastTouchY; // 上一个触摸点 Y

    private List<PointOne> pointOnes;

    private Gson gson;

    private Context context;

    private ScaleGestureDetector scaleGestureDetector;

    public MapEditView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        gson = new Gson();
        this.context = context;
        scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());
        pointOnes = new ArrayList<>();
    }

    public void setLaserData(JSONObject jsonObject,MapData mapData,List<PointOne> pointOnes) {
        this.jsonObjectScan = jsonObject;
        this.mapData = mapData;
        this.pointOnes = pointOnes;
        invalidate();  //绘制 调用draw
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        super.draw(canvas);

        // 创建画笔
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(5);  // 设置线条宽度
        paint.setStyle(Paint.Style.FILL);  // 设置绘制样式为填充

        // 将画布缩放到指定比例
//        canvas.scale(scaleFactor, scaleFactor, focusX, focusY);
//        canvas.translate(offsetX, offsetY);
//

        //不需要机器点位进行绘制
        if (jsonObjectScan != null) {
            //开始角
            float startAngle = Float.parseFloat(jsonObjectScan.getString("angle_min"));
            //自增角
            float incrementAngle = Float.parseFloat(jsonObjectScan.getString("angle_increment"));
            JSONArray dataArray = jsonObjectScan.getJSONArray("data");
            distances = new double[dataArray.size()];
            for (int i = 0; i < dataArray.size(); i++) {
                distances[i] = dataArray.getDouble(i) / 1000; // 转换为米
            }
            JSONObject laserPos = jsonObjectScan.getJSONObject("laserpos");
            float x = laserPos.getDouble("x").floatValue();
            float y = laserPos.getDouble("y").floatValue();
            double xRD = jsonObjectScan.getJSONObject("laserpos").getDouble("x");
            double yRD= jsonObjectScan.getJSONObject("laserpos").getDouble("y");
            xRD = switchX(xRD);
            yRD = switchY(yRD);
            float xR = (float) xRD;
            float yR = (float) yRD;
//            canvas.translate(-xR,-yR);
            for (int i = 0;i < distances.length; i++){
                double distance = distances[i];
                if (distance < 0.05) continue;
                double angle = startAngle + i * incrementAngle;
                float xx = (float) (distance * Math.cos(angle)) * 50;
                float yy = (float) (distance * Math.sin(angle)) * 50;
                Log.d("thd_","数据:"+ xx + getWidth() /2 +" " + yy + getHeight()/2);
                canvas.drawCircle(xx + getWidth()/2 , yy + getHeight()/2, 2, paint);  // 2表示点的半径
                //储存数据
                pointOnes.add(new PointOne(xx+ getWidth()/2,+ getHeight()/2));
            }
            //数据储存
            SPManager.savePoint(context,gson.toJson(pointOnes));

//
        }
    }

    private double switchX(double x){
        //世界坐标转为像素坐标
        x = (x - mapData.getOffx()) / mapData.getResolution();
        x = x- x * 2;
        return x;
    }

    private double switchY(double y){
        //世界坐标转为像素坐标
        y = (y - mapData.getOffy()) / mapData.getResolution();

        y = y- y * 2;
        return y;
    }

    private float switchX(float x){

        x = (float) ((x - mapData.getOffx()) / mapData.getResolution());
        x = x- x * 2;
        return x;
    }

    private float switchY(float y){

        y = (float) ((y - mapData.getOffy()) / mapData.getResolution());
        y = y- y * 2;
        return y;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        scaleGestureDetector.onTouchEvent(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastTouchX = event.getX();
                lastTouchY = event.getY();
                break;

            case MotionEvent.ACTION_MOVE:
                float dx = event.getX() - lastTouchX;
                float dy = event.getY() - lastTouchY;
                offsetX += dx; // 更新 X 轴偏移
                offsetY += dy; // 更新 Y 轴偏移
                lastTouchX = event.getX();
                lastTouchY = event.getY();
                invalidate(); // 重新绘制
                break;
        }
        return true; // 返回 true，表示事件已处理
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            scaleFactor *= detector.getScaleFactor(); // 更新缩放比例
            scaleFactor = Math.max(0.5f, Math.min(scaleFactor, 3.0f)); // 限制缩放范围
            focusX = detector.getFocusX(); // 获取缩放中心 X
            focusY = detector.getFocusY(); // 获取缩放中心 Y
            invalidate(); // 重新绘制
            return true;
        }
    }
}
